<?php

/**
 * Class Register_service 用户注册相关业务逻辑
 * @author: Calvin
 * @email : hongbinfu@163.com
 * @readme: 用户注册业务逻辑处理类
 */
class Register_service extends MY_Service
{
    public $tryout_cookie_key;
    public $is_tryout_session_key;
    private $register_uid=0;
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
        $this->config->load("user");
        $this->lang->load("user");
        $this->tryout_cookie_key = $this->config->item("tryout_cookie_key","login");
        $this->is_tryout_session_key = $this->config->item("is_tryout_session_key","login");
        $this->load->library("sms");
        $this->load->library("curl");
    }

    public function get_register_uid()
    {
        return $this->register_uid;
    }
    /**
     * 获取某个ip或者设备当天的注册数
     * @param $ip ip地址
     * @return bool|int
     */
    public function get_register_num($dev_md5="")
    {
        if(!empty($dev_md5))
        {
            $where['device_hash']=Common::time33($dev_md5);
            $where['device_md5']=$dev_md5;
        }
        else
        {
            $ip = $this->input->ip_address();
            $where['ip_hash']=Common::time33($ip);
            $where['ip']=$ip;
        }
        //查看数据该ip注册的记录
        $result = $this->user_model->get_register_log_info($where,"id,num,lasttime");
        if($result)
        {
            $exp = $this->config->item("register_log_exp_time","register");
            if(time() - $result['lasttime'] > $exp)
            {
                //1天后重新计算
                $this->user_model->delete_register_log(array("id"=>$result['id']));
            }
            else
            {
                return (int)$result['num'];
            }
        }
        return 0;
    }

    /**
     * 某ip注册用户是否检查验证码
     * @param $ip ip地址
     * @return bool
     */
    public function vcode_required($dev_md5=""){
        //一天内同一个ip注册允许免验证码检查次数
        $times = !empty($dev_md5)?$this->config->item("device_ignore_vcode_times","register"):$this->config->item("ip_ignore_vcode_times","register");
        if($times<=0)
        {
            return false;
        }
        $num = $this->get_register_num($dev_md5);
        if($num >0 && $num >= $times)
        {
            return $num;
        }
        else
        {
            return false;
        }
    }

    /**
     * 检查邮箱是否存在
     * @param $email
     * @return boolean
     */
    public function check_email_exists($email,$uid=FALSE)
    {
        if(empty($email))
        {
            return false;
        }
        $email = strtolower($email);
        $check = $this->user_model->get_user_info(array("email"=>$email),"id,verify");
        if($uid!==FALSE)
        {
            return !empty($check) && $check['id']!=$uid?$check:false;
        }
        else
        {
            return !empty($check)?$check:false;
        }
    }



    /**
     * 根据邮箱判断验证信息是否过期
     * @param $email
     * @return bool
     */
    public function check_overdue_by_email($email)
    {
        if(empty($email))
        {
            return $this->set_error(1003);
        }
        $email = strtolower($email);
        //注册流程，在指定时间内不激活则删除该账号
        $where=array(
            'process'=>1,//注册流程
            'way'=>1,//邮箱认证方式
            'receiver' => $email//邮箱账号
        );
        $find = $this->user_model->get_verify_info($where,'id,uid,num,time');
        $exp = $this->config->item('email_verify_code_exp','user_common');
        if(!empty($find) && time()-$find['time'] > $exp)
        {
            //过期未激活的用户将删除
            $this->user_model->delete_user($find['uid']);
            //删除验证记录
            $this->user_model->delete_verify_info(array("id"=>$find['id']));
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 通过邮箱注册账号
     * @param $email 邮箱
     * @param $password 密码
     * @param $ip ip地址
     * @param $n_phone 未验证的手机
     * @return boolean
     */
    public function register_by_email($email,$password,$n_phone="",$device_md5=""){
        if(empty($email) || empty($password))
        {
            return $this->set_error(1003);
        }
        $email = strtolower($email);
        $time = time();
        $capacity = $this->config->item("formal_user_capacity","register");
        $checkEmailExists = $this->check_email_exists($email);
        // && $this->check_overdue_by_email($email)===false
        //检查邮箱是否已经存在
        if($checkEmailExists)
        {
            return $this->set_error(5001);
        }

        if(!empty($n_phone) && $this->check_phone_exists($n_phone))
        {
            return $this->set_error(5009);
        }

        $data = array(
            'account_type'   => 1,
            'email'	         => $email,
            'n_mobile'        => $n_phone,
            'password'	     => md5($password),
            'regip'          => $this->input->ip_address(),
            'regtime'        => $time,
            'lasttime'	     => $time,
            'lastip'	     => $this->input->ip_address(),
            'capacity'       => $capacity
        );
        return $this->register($data,$device_md5);
    }

    public function register_by_phone($phone,$password,$n_email="",$device_md5="",$other_info=array(),$send_sms=FALSE)
    {
        if(empty($phone) || empty($password))
        {
            return $this->set_error(1003);
        }
        //检查手机是否存在
        if($this->check_phone_exists($phone))
        {
            return $this->set_error(5009);
        }

        //邮箱不为空是检查邮箱是否存在
        if(!empty($n_email) && $this->check_email_exists($n_email))
        {
            return $this->set_error(5001);
        }
        else if(!empty($n_email))
        {
            $n_email = strtolower($n_email);
        }
        //Common::console("邮箱：".$n_email,TRUE);
        $time=time();
        $capacity = $this->config->item("formal_user_capacity","register");
        $data = array(
            'account_type'   => 2,
            'mobile'         => $phone,
            'n_email'	     => $n_email,
            'verify'         => 1,
            'password'	     => md5($password),
            'regip'          => $this->input->ip_address(),
            'regtime'        => $time,
            'lasttime'	     => $time,
            'lastip'	     => $this->input->ip_address(),
            'capacity'       => $capacity
        );
        if(!empty($other_info)){
            $data = array_merge($data,$other_info);
        }
        $register =  $this->register($data,$device_md5);
        if($register && $send_sms){
            $tpl = $this->lang->line("sms_user_register_tpl");
            $content = sprintf($tpl,$phone,$password);
            $this->sms->send($phone,$content);
        }
        return $register;
    }

    public function check_phone_exists($mobile,$uid=FALSE)
    {
        if(empty($mobile))
        {
            return false;
        }
        $check = $this->user_model->get_user_info(array("mobile"=>$mobile),"id,verify");
        if($uid!==FALSE)
        {
            return !empty($check) && $check['id']!=$uid?$check:false;
        }
        else
        {
            return !empty($check)?$check:false;
        }

    }

    /**
     * 检查是否可以发送注册验证短信
     * @param $mobile
     * @return bool
     */
    /*public function can_send_register_sms($mobile)
    {
        //注册流程，在指定时间内不激活则删除该账号
        $where=array(
            'process'=>1,//注册流程
            'way'=>2,//短信认证方式
            'receiver' => $mobile//手机号
        );
        $find = $this->user_model->get_verify_info($where,'id,uid,num,time');
        $exp = $this->config->item('sms_verify_code_exp','user_common');
        if(!empty($find) && time()-$find['time'] > $exp)
        {
            //删除验证记录
            $this->user_model->delete_verify_info(array("id"=>$find['id']));
            return true;
        }
        else
        {
            return false;
        }
    }*/


    /**
     * 统一的注册函数
     * @param $data 注册的数据
     * @param bool $tryout_uniqid 试用用户的uniqid（从试用用户转正）
     * @return bool
     */
    private function register($data,$device_md5="")
    {
        $user_model = $this->user_model;
        $tryout_uniqid = $this->input->cookie($this->tryout_cookie_key);
        //从试用用户转正
        if(!empty($tryout_uniqid))
        {
            //获取试用用户的id
            $tryout_user_info =  $user_model->get_user_info_by_uniqid($tryout_uniqid,"id,account_type");
            //var_dump(!empty($tryout_user_info) && $tryout_user_info['account_type']==0);exit;
            if($tryout_user_info===false)
            {
                return $this->set_error(1002);
            }
            else if(!empty($tryout_user_info) && $tryout_user_info['account_type']==0)//排除已经转正的用户
            {
                $result = $this->user_model->update($tryout_user_info['id'], $data);
                if($result === false)
                {
                    return $this->set_error(1002);
                }
                else
                {
                    $this->register_uid=$tryout_user_info['id'];
                    return $this->add_log($device_md5);
                }
            }
            else
            {
                $this->input->set_cookie($this->tryout_cookie_key, '', time()-3600,'', '/');
            }
        }

        //新建用户信息
        $data['uniqid'] = Common::uniqid();
        $create_user_info = $user_model->insert($data);
        if($create_user_info===false)
        {
            return $this->set_error(1002);
        }
        else
        {
            $this->register_uid = $user_model->get_insert_id();
            return $this->add_log($device_md5);
        }
    }

    /**
     * 添加注册日志(用于限制同一ip或者同一设备的注册次数或者是否显示验证码)
     * @param $ip ip地址
     * @param $dev_md5 设备md5值
     */
    private function add_log($dev_md5="")
    {
        $ip = $this->input->ip_address();
        $old_num = $this->get_register_num($dev_md5);
        $num = $old_num+1;
        $data = array(
            'type'  =>1,
            'ip'	=> $ip,
            'ip_hash'	=> Common::time33($ip),
            'num'	=> $num,
            'device_md5'=>$dev_md5,
            'device_hash'=>Common::time33($dev_md5),
            'lasttime'	=> time()
        );

        if(!empty($dev_md5))
        {
            $where = array(
                'device_hash'=>$data['device_hash'],
                "device_md5" =>$data['device_md5']
            );
        }
        else
        {
            $where=array(
                'ip_hash'	=> $data['ip_hash'],
                "ip"=>$data['ip']
            );
        }

        if($old_num>0)
        {
            $result = $this->user_model->update_register_log($where, $data);
        }
        else
        {
            $result = $this->user_model->insert_register_log($data);
        }
        //var_dump($where);
        if($result === false)
        {
            return $this->set_error(1002);
        }
        else
        {
            $del_login_error_log = $this->user_model->delete_login_error_log($where);
            if($del_login_error_log===false)
            {
                return $this->set_error(1002);
            }
            else
            {
                return true;
            }
        }
    }

    /**
     * 通过email获取校验信息
     * @param $email
     * @param string $field
     * @return mixed
     */
    public function get_verify_info_by_email($email,$field="id,num,time"){
        $where=array(
            'process'=>1,
            'way'   =>1,
            'receiver'=>$email
        );
        return $this->user_model->get_verify_info($where,$field);
    }

    /**
     * 删除注册检查日志
     * @param string $dev_md5
     * @return mixed
     */
    public function delete_register_log($dev_md5="")
    {
        return $this->user_model->fast_delete_register_log($dev_md5);
    }


    public function active_user_by_email($email)
    {
        return $this->user_model->update_user_info(array("email"=>$email),array("verify"=>1));
    }



}
